package com.cnbot.dchttpsdk.download;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.cnbot.dchttpsdk.helper.DownFileProgressListener;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * Copyright (c) 2016-a  Hunan Cnbot Co., Ltd. All Rights Reserved.
 *
 * @descriptoin 下载
 * @FileName: DownloadProgressResponseBody.java
 * @author: dc
 * @date: 2019/1/19 14:11
 * @version: 1.0
 */

public class DownloadProgressResponseBody extends ResponseBody {
    private ResponseBody responseBody;
    private DownFileProgressListener progressListener;
    private BufferedSource bufferedSource;
    private final Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {

            Bundle bundle = msg.getData();

            progressListener.onProgress(bundle.getLong("progress"), bundle.getLong("length"), bundle.getBoolean("isDone"));

        }
    };
    public DownloadProgressResponseBody(ResponseBody responseBody, DownFileProgressListener progressListener) {
        this.responseBody = responseBody;
        this.progressListener = progressListener;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                // read() returns the number of bytes read, or -1 if this source is exhausted.
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;

                if (null != progressListener) {
                    //进度信息回调
                    sendMsg(totalBytesRead,bytesRead==-1);
                }
                Log.e("source","progress:" + totalBytesRead);
                return bytesRead;
            }

        };

    }

    private void sendMsg(long progress, boolean flag) {
        Message message = mHandler.obtainMessage();
        Bundle bundle  = new Bundle();
        bundle.putLong("progress", progress);
        bundle.putLong("length", responseBody.contentLength());
        bundle.putBoolean("isDone",flag);
        message.setData(bundle);
        mHandler.sendMessage(message);
    }
}
